package com.netty.chatRoom.server.Handler;

import com.netty.chatRoom.message.GroupQuitRequestMessage;
import com.netty.chatRoom.message.GroupQuitResponseMessage;
import com.netty.chatRoom.server.session.GroupSession;
import com.netty.chatRoom.server.session.GroupSessionFactory;
import com.netty.chatRoom.server.session.SessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Set;

@ChannelHandler.Sharable
public class GroupQuitRequestMessageHandler extends SimpleChannelInboundHandler <GroupQuitRequestMessage>{
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, GroupQuitRequestMessage groupQuitRequestMessage) throws Exception {
        String groupName = groupQuitRequestMessage.getGroupName();
        String username = groupQuitRequestMessage.getUsername();
        Set<String> members = GroupSessionFactory.getGroupSession().getMembers(groupName);
        if (members.size()<=0){
            channelHandlerContext.writeAndFlush(new GroupQuitResponseMessage(false,String.format("群聊【%s】不存在",groupName)));
        }else {
            GroupSessionFactory.getGroupSession().removeMember(groupName,username);
            channelHandlerContext.writeAndFlush(new GroupQuitResponseMessage(true,String.format("退出群聊【%s】成功",groupName)));
            for (String member : members) {
                if(!member.equals(username)){
                    Channel channel = SessionFactory.getSession().getChannel(member);
                    if (channel!=null){
                        channel.writeAndFlush(new GroupQuitResponseMessage(true,String.format("用户【%s】已退出群聊【%s】",username,groupName)));
                    }
                }
            }
        }
    }
}
